#include "industrial_robot_control/visualization/web_server.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <chrono>
#include <thread>

// 简单的HTTP服务器实现
namespace http {
    struct server {
        using request_handler = std::function<std::string(const std::string&, const std::string&)>;
        
        server(int port, request_handler handler) 
            : port_(port), handler_(handler), running_(false) {}
        
        void run() {
            running_ = true;
            // 实际应用中应实现完整的HTTP服务器
            std::cout << "HTTP服务器运行在端口 " << port_ << std::endl;
            
            while (running_) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
        }
        
        void stop() {
            running_ = false;
        }
        
    private:
        int port_;
        request_handler handler_;
        std::atomic<bool> running_;
    };
}

namespace industrial_robot_control {
namespace visualization {

WebServer::WebServer() {
}

WebServer::~WebServer() {
    stop();
}

bool WebServer::start(int port) {
    try {
        if (running_) {
            return true;
        }
        
        port_ = port;
        
        // 初始化WebSocket服务器
        ws_server_ = std::make_shared<websocket_server>();
        ws_server_->init_asio();
        ws_server_->set_open_handler(std::bind(&WebServer::onWebSocketOpen, this, std::placeholders::_1));
        ws_server_->set_close_handler(std::bind(&WebServer::onWebSocketClose, this, std::placeholders::_1));
        ws_server_->set_message_handler(std::bind(&WebServer::onWebSocketMessage, this, 
                                                std::placeholders::_1, std::placeholders::_2));
        
        // 初始化HTTP服务器
        http_server_ = std::make_shared<http::server>(port, 
                                                    std::bind(&WebServer::onHttpRequest, this, 
                                                              std::placeholders::_1, std::placeholders::_2));
        
        running_ = true;
        server_thread_ = std::make_unique<std::thread>(&WebServer::runServer, this);
        
        std::cout << "Web服务器已启动，端口: " << port << std::endl;
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Web服务器启动错误: " << e.what() << std::endl;
        stop();
        return false;
    }
}

void WebServer::stop() {
    if (running_) {
        running_ = false;
        
        if (ws_server_) {
            ws_server_->stop_listening();
            ws_server_->stop();
        }
        
        if (http_server_) {
            http_server_->stop();
        }
        
        if (server_thread_ && server_thread_->joinable()) {
            server_thread_->join();
        }
        
        ws_server_.reset();
        http_server_.reset();
        connections_.clear();
        
        std::cout << "Web服务器已停止" << std::endl;
    }
}

void WebServer::processRequests() {
    // 定期推送数据给客户端
    if (data_callback_ && !connections_.empty()) {
        try {
            json data = data_callback_();
            broadcastMessage(data);
        } catch (const std::exception& e) {
            std::cerr << "Web数据回调错误: " << e.what() << std::endl;
        }
    }
}

void WebServer::broadcastMessage(const json& message) {
    std::lock_guard<std::mutex> lock(connections_mutex_);
    
    std::string msg_str = message.dump();
    for (auto it = connections_.begin(); it != connections_.end();) {
        try {
            ws_server_->send(*it, msg_str, websocketpp::frame::opcode::text);
            ++it;
        } catch (const std::exception& e) {
            std::cerr << "WebSocket发送错误: " << e.what() << std::endl;
            it = connections_.erase(it);
        }
    }
}

void WebServer::runServer() {
    try {
        // 启动WebSocket监听
        ws_server_->listen(port_);
        ws_server_->start_accept();
        
        // 运行HTTP服务器
        std::thread http_thread(&http::server::run, http_server_);
        
        // 运行WebSocket IO服务
        ws_server_->run();
        
        // 等待HTTP服务器线程结束
        if (http_thread.joinable()) {
            http_thread.join();
        }
    } catch (const std::exception& e) {
        std::cerr << "Web服务器运行错误: " << e.what() << std::endl;
    }
}

void WebServer::onWebSocketOpen(websocketpp::connection_hdl hdl) {
    std::lock_guard<std::mutex> lock(connections_mutex_);
    connections_.insert(hdl);
    std::cout << "WebSocket客户端已连接" << std::endl;
    
    // 发送欢迎消息
    json welcome;
    welcome["type"] = "welcome";
    welcome["message"] = "连接到工业机器人控制系统";
    welcome["version"] = "2.0.0";
    
    try {
        ws_server_->send(hdl, welcome.dump(), websocketpp::frame::opcode::text);
    } catch (const std::exception& e) {
        std::cerr << "WebSocket发送欢迎消息错误: " << e.what() << std::endl;
    }
}

void WebServer::onWebSocketClose(websocketpp::connection_hdl hdl) {
    std::lock_guard<std::mutex> lock(connections_mutex_);
    connections_.erase(hdl);
    std::cout << "WebSocket客户端已断开连接" << std::endl;
}

void WebServer::onWebSocketMessage(websocketpp::connection_hdl hdl, websocket_server::message_ptr msg) {
    try {
        std::string payload = msg->get_payload();
        json request = json::parse(payload);
        
        std::cout << "收到WebSocket消息: " << payload << std::endl;
        
        // 处理客户端请求
        json response;
        response["type"] = "response";
        
        if (request.contains("command")) {
            std::string command = request["command"];
            
            if (command == "get_status") {
                if (data_callback_) {
                    response["data"] = data_callback_();
                } else {
                    response["error"] = "没有注册数据回调";
                }
            }
            else {
                response["error"] = "未知命令: " + command;
            }
        } else {
            response["error"] = "缺少命令字段";
        }
        
        ws_server_->send(hdl, response.dump(), websocketpp::frame::opcode::text);
    } catch (const std::exception& e) {
        std::cerr << "处理WebSocket消息错误: " << e.what() << std::endl;
        
        json error_response;
        error_response["type"] = "error";
        error_response["message"] = e.what();
        
        try {
            ws_server_->send(hdl, error_response.dump(), websocketpp::frame::opcode::text);
        } catch (...) {
            // 忽略发送错误
        }
    }
}

std::string WebServer::onHttpRequest(const std::string& path, const std::string& method) {
    // 简单的HTTP请求处理
    std::stringstream response;
    
    if (method == "GET") {
        if (path == "/" || path == "/index.html") {
            // 返回主页面
            response << "HTTP/1.1 200 OK\r\n";
            response << "Content-Type: text/html\r\n";
            response << "\r\n";
            response << "<html><head><title>工业机器人控制系统</title></head>";
            response << "<body><h1>工业机器人控制系统</h1>";
            response << "<p>请使用WebSocket连接到ws://localhost:" << port_ << "</p>";
            response << "</body></html>";
        } else {
            // 页面未找到
            response << "HTTP/1.1 404 Not Found\r\n";
            response << "Content-Type: text/plain\r\n";
            response << "\r\n";
            response << "页面未找到: " << path;
        }
    } else {
        // 方法不支持
        response << "HTTP/1.1 405 Method Not Allowed\r\n";
        response << "Content-Type: text/plain\r\n";
        response << "\r\n";
        response << "不支持的方法: " << method;
    }
    
    return response.str();
}

} // namespace visualization
} // namespace industrial_robot_control
